package com.njit.postbar.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendCode {

    public static void send(String mailTo,String code)throws Exception{

        // 发件人电子邮箱
        String from = "xxx@qq.com";
        // 获取系统属性
        Properties properties = new Properties();
        // 设置邮件服务器
        properties.setProperty("mail.transport.protocol", "SMTP");
        properties.setProperty("mail.smtp.host", "smtp.qq.com");
        properties.setProperty("mail.smtp.port", "25");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.timeout", "1000");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        // 登陆邮件发送服务器的用户名和密码
                        return new PasswordAuthentication("xxx@qq.com", "xxx");
                    }
                });
        // 创建默认的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);
        // Set From: 头部头字段
        message.setFrom(new InternetAddress(from));
        // Set To: 头部头字段
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        // Set Subject: 头部头字段
        message.setSubject("验证码:"+code);
        // 设置消息体
        message.setText(code);
        // 发送消息
        Transport.send(message);
    }
}
